rm(list=ls())
library(dplyr)
#set working directory
main_dir = "...\\Source Data\\Additional Data\\News Coverage\\"
setwd(main_dir)

#load lexus data results
load("nexus_data.RDA")

#articles mentioning Judge Persky
final_data <- subset(final_data,persky_mentioned==1)
final_data$week <- lubridate::floor_date(final_data$dates, "weeks") 
paper_tally= final_data %>%
  group_by(week) %>% tally()

#google trends coverage of Judge Perksy
trends<- read.csv("google trends.csv")
trends$week <- as.Date(trends$Week,format="%m/%d/%Y")
trends$trends = trends$judge.persky...United.States.
trends$trends[trends$trends=="<1"]=0
trends$trends <- as.numeric(trends$trends)

#combine articles and google searches
combined <- merge(trends[,c("week","trends")],paper_tally,by = "week",all = T)
combined$n[is.na(combined$n)]=0

#filter between 2016-2019
combined = subset(combined,week<as.Date("01/01/2019",format="%m/%d/%Y")&
                    week>=as.Date("01/01/2016",format="%m/%d/%Y"))
combined$n_normed = 100*combined$n/max(combined$n,na.rm = T)

#Figure A.1
ggplot(combined) +
  geom_line(mapping=aes(x=week, y=n_normed,color="Y1"),size=0.5)+
  geom_line(mapping=aes(x=week, y=trends,color ="Y2"),size=0.5,linetype="solid")+
  #geom_line(mapping=aes(x=dates, y=petition,color="Y2"),size=0.5) + 
  scale_color_manual(name = "", values = c("Y1"="black", "Y2"="maroon"),
                     labels = c("News Articles","Google Searches"))+
  xlab("")+ylab("Judge Persky's Media Salience, by Week")+
  geom_vline(xintercept = as.Date("2016-06-06"),linetype="dashed",color="gray",size=0.5)+
  geom_vline(xintercept = as.Date("2018-01-24"),linetype="dashed",color="gray",size=0.5)+
  geom_vline(xintercept = as.Date("2018-06-05"),linetype="dashed",color="gray",size=0.5)+
  theme_minimal() + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"),
        axis.text.x=element_text(angle = 45, hjust = 1),
        legend.position=c(0.9, 0.9),legend.margin=margin(0,0,0,0))+
  scale_x_date(
    breaks = c(
      as.Date("2016-01-01",origin="2016-05-15"),as.Date("2016-06-06",origin="2016-05-15"),
      as.Date("2017-01-01",origin="2016-05-15"),as.Date("2018-01-01",origin="2016-05-15"),
      as.Date("2018-01-24",origin="2016-05-15"),as.Date("2018-06-05",origin="2016-05-15"),
      as.Date("2019-01-01",origin="2016-05-15")),
    labels = c("2016","Petition \n Announced",
               "2017", "2018",
               "Signatures \n Certified","Recall \n Election",
               "2019"))


ggsave(plot=last_plot(),file="news_articles.pdf",height=5,width=8)

